package com.kinptm.masterclock.ui.fragment;

import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.actionbarsherlock.app.SherlockFragment;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.kinptm.masterclock.R;
import com.kinptm.masterclock.adapter.HolderViewFiller;
import com.kinptm.masterclock.adapter.item.StopWatchItemBuilder;
import com.kinptm.masterclock.bean.IntervalTime;
import com.kinptm.masterclock.bean.SpeedTime;
import com.kinptm.masterclock.bean.StopWatchRecord;
import com.kinptm.masterclock.utils.Ln;
import com.kinptm.masterclock.utils.TimeUtil;
import com.kinptm.masterclock.utils.ViewUtil;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by pc on 13-11-7.
 */
public class StopWatchFragment extends SherlockFragment implements View.OnClickListener {
    private static final String IS_STOPWATCH_STARTING = "is_stopwatch_starting";
    private static final String CONSUME_TIME = "consume_time";
    private static final String CONSUME_SUB_TIME = "consume_sub_time";
    private static final String RECORDS = "records";

    private TextView mHourTextView;
    private TextView mMinuteTextView;
    private TextView mSecondTextView;
    private TextView mMillisTextView;

    private TextView mHourSubTextView;
    private TextView mMinuteSubTextView;
    private TextView mSecondSubTextView;
    private TextView mMillisSubTextView;
    private ViewFlipper mControlViewFlipper;

    private ListView mRecordsListView;
    private List<StopWatchRecord> mRecords;
    private HolderViewFiller<StopWatchRecord> mHolderViewFiller;
    private boolean isStopWatchStarting = false;

    private IntervalTime mIntervalTime;
    private IntervalTime mIntervalSubTime;
    private Timer mTimer;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            long currentTimeMillis = (Long) msg.obj;

            mIntervalTime.setEndTime(currentTimeMillis);
            mIntervalSubTime.setEndTime(currentTimeMillis);
            updateViews(mIntervalTime);
            updateSubViews(mIntervalSubTime);
        }
    };


    public static StopWatchFragment newInstance() {
        StopWatchFragment fragment = new StopWatchFragment();
//        Bundle bundle = new Bundle();
//        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_stopwatch, container, false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        mHourTextView = ViewUtil.findView(view, R.id.stopwatch_hour_tv);
        mMinuteTextView = ViewUtil.findView(view, R.id.stopwatch_minute_tv);
        mSecondTextView = ViewUtil.findView(view, R.id.stopwatch_second_tv);
        mMillisTextView = ViewUtil.findView(view, R.id.stopwatch_millis_tv);

        mHourSubTextView = ViewUtil.findView(view, R.id.stopwatch_sub_hour_tv);
        mMinuteSubTextView = ViewUtil.findView(view, R.id.stopwatch_sub_minute_tv);
        mSecondSubTextView = ViewUtil.findView(view, R.id.stopwatch_sub_second_tv);
        mMillisSubTextView = ViewUtil.findView(view, R.id.stopwatch_sub_millis_tv);

        mControlViewFlipper = ViewUtil.findView(view, R.id.stopwatch_controler_vf);
        mRecordsListView = ViewUtil.findView(view, R.id.stopwatch_records_lv);

        ViewUtil.findViewAndClick(view, R.id.stopwatch_start_btn, this);
        ViewUtil.findViewAndClick(view, R.id.stopwatch_clear_btn, this);
        ViewUtil.findViewAndClick(view, R.id.stopwatch_stop_btn, this);
        ViewUtil.findViewAndClick(view, R.id.stopwatch_record_btn, this);

        setTypeface(mHourTextView, mMinuteTextView, mSecondTextView, mMillisTextView, mHourSubTextView, mMinuteSubTextView, mSecondSubTextView, mMillisSubTextView);

    }


    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Gson gson = new Gson();
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
        isStopWatchStarting = preferences.getBoolean(IS_STOPWATCH_STARTING, false);
        mIntervalTime = gson.fromJson(preferences.getString(CONSUME_TIME, "{}"), IntervalTime.class);
        mIntervalSubTime = gson.fromJson(preferences.getString(CONSUME_SUB_TIME, "{}"), IntervalTime.class);
        mRecords = gson.fromJson(preferences.getString(RECORDS, "[]"), new TypeToken<List<StopWatchRecord>>() {
        }.getType());

        mHolderViewFiller = new HolderViewFiller<StopWatchRecord>(getLayoutInflater(savedInstanceState), new StopWatchItemBuilder());
        mHolderViewFiller.update(mRecordsListView, mRecords);
    }

    private void setTypeface(TextView... tvs) {
        Typeface fontFace = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Transist.ttf");
        for (TextView tv : tvs) {
            tv.setTypeface(fontFace);
        }
    }

    private void updateViews(IntervalTime intervalTime) {
        SpeedTime time = intervalTime.getTime();
        ViewUtil.setText(mHourTextView, TimeUtil.keepTwoNum(time.getHour()));
        ViewUtil.setText(mMinuteTextView, TimeUtil.keepTwoNum(time.getMinute()));
        ViewUtil.setText(mSecondTextView, TimeUtil.keepTwoNum(time.getSecond()));
        ViewUtil.setText(mMillisTextView, TimeUtil.keepTwoNum(time.getMillis()));
    }

    private void updateSubViews(IntervalTime intervalTime) {
        SpeedTime time = intervalTime.getTime();
        ViewUtil.setText(mHourSubTextView, TimeUtil.keepTwoNum(time.getHour()));
        ViewUtil.setText(mMinuteSubTextView, TimeUtil.keepTwoNum(time.getMinute()));
        ViewUtil.setText(mSecondSubTextView, TimeUtil.keepTwoNum(time.getSecond()));
        ViewUtil.setText(mMillisSubTextView, TimeUtil.keepTwoNum(time.getMillis()));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.stopwatch_start_btn: {
                mControlViewFlipper.setDisplayedChild(1);
                startStopWatch(false);
                isStopWatchStarting = true;
                break;
            }
            case R.id.stopwatch_clear_btn:
                if (mIntervalTime != null) {
                    mIntervalTime.reset();
                    mIntervalSubTime.reset();
                    updateViews(mIntervalTime);
                    updateSubViews(mIntervalSubTime);
                }
                mRecords.clear();
                mHolderViewFiller.exportAdapter(mRecordsListView).notifyDataSetChanged();
                break;
            case R.id.stopwatch_stop_btn: {
                mControlViewFlipper.setDisplayedChild(2);
                cancelStopWatch();
                isStopWatchStarting = false;
                break;
            }
            case R.id.stopwatch_record_btn:
                StopWatchRecord record = new StopWatchRecord(mIntervalSubTime.getSpendTime(), mIntervalTime.getSpendTime());
                mRecords.add(record);
                mHolderViewFiller.exportAdapter(mRecordsListView).notifyDataSetChanged();
                mRecordsListView.setSelection(mRecordsListView.getCount() - 1);

                mIntervalSubTime.setStartTime(System.currentTimeMillis());
                break;
        }
    }

    /**
     * 开始计时
     *
     * @param includeSpeedTime 是否包括暂停的时间
     */
    private void startStopWatch(boolean includeSpeedTime) {
        cancelStopWatch();
        mTimer = new Timer();
        StopWatchTimerTask timerTask = new StopWatchTimerTask();
        mTimer.schedule(timerTask, 0, 10);
        long currentTimeMillis = System.currentTimeMillis();
        long startTime = mIntervalTime.getStartTime();
        long subStartTime = mIntervalSubTime.getStartTime();

        //计算方式 : 包括暂停的时间--startTime不变 , 不包括暂停的时间-- startTime = currentTimeMillis-spendTime(); 当前时间-已花费时间
        startTime = startTime == 0 ? currentTimeMillis : (includeSpeedTime ? startTime : (currentTimeMillis - mIntervalTime.getSpendTime()));
        subStartTime = subStartTime == 0 ? currentTimeMillis : (includeSpeedTime ? subStartTime : (currentTimeMillis - mIntervalSubTime.getSpendTime()));

        mIntervalTime.setStartTime(startTime);
        mIntervalSubTime.setStartTime(subStartTime);
    }

    private void cancelStopWatch() {
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        Ln.d("onResume");
        if (isStopWatchStarting) {
            startStopWatch(true);
            mControlViewFlipper.setDisplayedChild(1);
        } else {
            mControlViewFlipper.setDisplayedChild(2);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        Ln.d("onPause");
        cancelStopWatch();
        Gson gson = new Gson();
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
        preferences.edit().putBoolean(IS_STOPWATCH_STARTING, isStopWatchStarting).putString(CONSUME_TIME, gson.toJson(mIntervalTime))
                .putString(CONSUME_SUB_TIME, gson.toJson(mIntervalSubTime)).putString(RECORDS, gson.toJson(mRecords)).commit();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        cancelStopWatch();
    }

    class StopWatchTimerTask extends TimerTask {
        @Override
        public void run() {
            Message message = mHandler.obtainMessage(1);
            message.obj = System.currentTimeMillis();
            mHandler.sendMessage(message);
        }
    }
}